<?php
namespace qhweb\phpsm\test;

use PHPUnit\Framework\TestCase;
use qhweb\phpsm\sm\SM2;
use qhweb\phpsm\sm\SM3;
use qhweb\phpsm\sm\SM4;
class SmTest extends TestCase
{
    public function testSmInstantiation()
    {
        // 使用示例
        try {
            $key = '1234567890abcdef'; // 16 字节
            $iv = 'abcdefghijklmnop';  // 16 字节

            $sm2 = new SM2();
            echo "=== SM3 ===\n\n";
            echo '普通加密:'.SM3::hash('admin123'). "\n";
            echo '填充加密:'.SM3::hmac('admin123',$key). "\n";

            // 1. 生成密钥对
            echo "=== SM2密钥生成 ===\n\n";
            [$privateKey, $publicKey] = createSm2KeyPem();
            var_dump($privateKey, $publicKey);
            $privateKey = '2bc313584c9aece21b1c3cf7b8b7fa5561612d82c2b823067452ff396edcaec9';
            $publicKey = '0423652d9339b008e8861eec73633ea0c50726d5f478f6db9699cbe3f1a9052f4bfbc345600b53dfd6bac616cb9909e89bdfd094163669d7ed191b51626baa26a0';
            echo "私钥:\n" . $privateKey . "\n";
            echo "公钥:\n" . $publicKey . "\n";
            
            // 2. 测试数据
            $testData = "hello world!";
            echo "原始数据: " . $testData . "\n";
            
            // 3. 加密解密测试
            echo "=== SM2加密解密测试 ===\n\n";
            $encryptResult = $sm2->doEncrypt($testData, $publicKey);
            echo "加密结果: " . $encryptResult. "\n";


            $decryptResult = $sm2->doDecrypt($encryptResult,$privateKey);
            echo "解密结果: " . $decryptResult . "\n";
            
            // 4. 数字签名测试
            echo "=== SM2数字签名测试 ===\n\n";
            $signResult = $sm2->doSign($testData,$privateKey);
            echo "签名结果: " . $signResult . "\n";
            
            // 5. 签名验证测试
            $verifyResult = $sm2->verifySign($testData, $signResult,$publicKey);
            echo "签名验证: " . ($verifyResult ? "成功" : "失败") . "\n";

            echo "=== SM4测试 ===\n\n";
            $sm4 = new SM4($key);
            $types = ['cbc','ecb','ctr','ofb','cfb'];
            $data = json_encode(["a"=>1,"b"=>2]);
            foreach ($types as  $type) {
                $encryptData = sm4Encrypt($data,'sm4-'.$type,$iv);
                $decryptData = $sm4->decrypt($encryptData,'sm4-'.$type,$iv);
                echo "=== [$type] ===\n";
                echo $type."加密结果: " . $encryptData . "\n";
                echo $type."解密结果: " . $decryptData . "\n";
            }
            

        } catch (\Exception $e) {
            echo "错误: " . $e->getMessage() . "\n";
        }
    }
}


